﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using ESoft.DataAccess.Models;

namespace ESoft.DataAccess.EfCore.MySql
{
    /// <summary>
    /// mysql SQL查询类
    /// </summary>
    public class MySqlQueryRepositry : BaseSqlQueryRepositry, ISqlRepositry
    {
        /// <summary>
        /// 初始化
        /// </summary>
        /// <param name="db"></param>
        public MySqlQueryRepositry(DataContext db) : base(db)
        {
        }

        /// <summary>
        /// 分页获取数据信息
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="query"></param>
        /// <param name="pageInput"></param>
        /// <param name="orderBy"></param>
        /// <param name="parameters"></param>
        /// <returns></returns>
        public override PageResult<T> FindPageBySql<T>(string query, PageInput pageInput, string orderBy,
            params object[] parameters)
        {
            string pageSql = $"{query} ORDER BY {orderBy}  limit {pageInput.Page - 1},{pageInput.Limit}";

            List<T> items = FindBySql<T>(pageSql, parameters);

            string countSql = $"SELECT count(*) FROM ({query}) as T";
            int count = ExecuteScalar<int>(countSql, parameters);

            return new PageResult<T>(items, count);
        }

        /// <summary>
        /// 异步获取分页信息
        /// </summary>
        /// <param name="rawSql"></param>
        /// <param name="pageInput"></param>
        /// <param name="orderBy"></param>
        /// <param name="parameters"></param>
        /// <typeparam name="T"></typeparam>
        /// <returns></returns>
        public override async Task<PageResult<T>> FindPageBySqlAsync<T>(string rawSql, PageInput pageInput,
            string orderBy, params object[] parameters)
        {
            var pageSql = $"{rawSql} ORDER BY {orderBy}  limit {pageInput.Page - 1},{pageInput.Limit}";

            var items = await FindBySqlAsync<T>(pageSql, parameters);

            var countSql = $"SELECT count(*) FROM ({rawSql}) as T";
            var count = await ExecuteScalarAsync<int>(countSql, parameters);

            return new PageResult<T>(items, count);
        }
    }
}